package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author sunhui
 * @since 2024-03-28
 */
@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {

        //1、参数校验
        if(Objects.isNull(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Map<String, Object> resultMap = new HashMap<>();
        if(StringUtils.isNotBlank(dto.getPhone()) //手机号
            && StringUtils.isNotBlank(dto.getPassword()) //密码，是未加密的
        ) {
            //2、根据手机号查询用户
            LambdaQueryWrapper<ApUser> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUserFromDB = this.getOne(queryWrapper);
            //2。1 判断用户是否存在
            if(Objects.isNull(apUserFromDB)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //2.2密码对比
            String pwdAndSalt = dto.getPassword() + apUserFromDB.getSalt();//密码，是未加密的，密码，通信等加密盐
            String pwd = DigestUtils.md5DigestAsHex(pwdAndSalt.getBytes(StandardCharsets.UTF_8));
            if(!pwd.equals(apUserFromDB.getPassword())) {
                return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //2.3判断用户状态
            if(!apUserFromDB.getStatus()) {
                return ResponseResult.errorResult(AppHttpCodeEnum.USER_STATUS_EX);
            }
            //3、封装数据
            String token = AppJwtUtil.getToken(apUserFromDB.getId().longValue());
            resultMap.put("token", token);
            apUserFromDB.setPassword("");
            apUserFromDB.setSalt("");
            resultMap.put("user", apUserFromDB);
        } else {
            String token = AppJwtUtil.getToken(0L);
            resultMap.put("token", token);
        }
        return ResponseResult.okResult(resultMap);
    }
}
